#include "EchoServer.h"
#include "TcpConnection.h"
#include "ThreadPool.h"
#include "MyTask.h"

EchoServer::EchoServer(const std::string& ip,uint16_t port)
:_server(ip,port),
_pool(ThreadPool::getInstance())
{
    //设置回调函数
    _server.setAllCallback(std::bind(&EchoServer::onNewConnection,this,std::placeholders::_1),
                            std::bind(&EchoServer::onMessage,this,std::placeholders::_1),
                            std::bind(&EchoServer::onClose,this,std::placeholders::_1));
}
EchoServer::~EchoServer()
{

}
void EchoServer::start()
{
    _pool->start();
    _server.start();
}
void EchoServer::stop()
{
    _server.stop();
    _pool->stop();
}

//新的连接建立时TcpConnection会触发的一些动作
void EchoServer::onNewConnection(const TcpConnectionPtr& conn)
{
    std::cout<<"new connection "<<conn->toString()<<std::endl;
}


void EchoServer::onMessage(const TcpConnectionPtr& conn)
{
    //read数据
    std::string msg = conn->receive();
    std::cout<<">>receive message = "<<msg<<std::endl;
    //将任务添加到线程池
    _pool->addTask(std::make_shared<MyTask>(conn,msg));
}
void EchoServer::onClose(const TcpConnectionPtr& conn)
{
    std::cout<<"close connection "<<std::endl;
}
